package cn.silky.demo.web.entity;

import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Getter;
import lombok.Setter;
import lombok.experimental.Accessors;
import org.springframework.data.annotation.Id;
import org.springframework.data.annotation.Transient;
import org.springframework.data.relational.core.mapping.Table;
import org.springframework.lang.NonNull;
import org.springframework.security.core.authority.SimpleGrantedAuthority;

import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;


/**
 * <p>
 * 用户表
 * </p>
 *
 * @author ListJiang
 * @since 2021-11-01
 */
@Getter
@Setter
@Accessors(chain = true)
@Table("sys_user")
public class SysUser implements Serializable {

    private static final long serialVersionUID = 1L;

    /**
     * 主键id
     */
    @Id
    private Long id;

    /**
     * 账号id
     */
    private Long accountId;

    /**
     * 昵称
     */
    private String nickName;

    /**
     * 年龄
     */
    private Integer age;

    /**
     * 创建人账号id
     */
    private Long creator;

    /**
     * 创建时间
     */
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    private LocalDateTime creteTime;

    /**
     * 修改人账号id
     */
    private Long modifiedBy;

    /**
     * 逻辑删除标识：1，删除。0，未删除
     */
    private Byte deleted;

    public boolean isDeleted() {
        return deleted != null && deleted != 0;
    }

    public void setDeleted(boolean deleted) {
        this.deleted = (byte) (deleted ? 1 : 0);
    }

    /**
     * 角色
     */
    @Transient
    private List<SysRole> sysRoles;

    public SysUser setSysRoles(@NonNull List<SysRole> sysRoles) {
        this.sysRoles = sysRoles;
        if (authorities == null) {
            authorities = new ArrayList<>();
        } else {
            authorities.clear();
        }
        sysRoles.forEach(sysRole -> {
            authorities.add(new SimpleGrantedAuthority("ROLE_" + sysRole.getName()));
            sysRole.getSysPermissions().forEach(sysPermission -> {
                // 不是以”/“开头的是通用权限，例如”read“，以”/“开头的则是接口地址
                if (!sysPermission.getName().startsWith("/")) {
                    authorities.add(new SimpleGrantedAuthority(sysPermission.getName()));
                }
            });
        });
        return this;
    }

    @Transient
    private Collection<SimpleGrantedAuthority> authorities;

    public Collection<SimpleGrantedAuthority> getAuthorities() {
        return authorities;
    }
}